#!/bin/bash
#
# Init file for Gfarm filesystem node daemon
#
# chkconfig: 2345 95 05
# description: Gfarm filesystem node daemon
#
# processname: gfsd
# config: /etc/gfarm2.conf
# pidfile: /var/run/<%= @gfsd_service %>.pid
#
# $Id: gfsd.in 4167 2009-05-24 01:52:22Z tatebe $

# source function library
. /etc/rc.d/init.d/functions

prog="gfsd"
FILE="<%= @gfsd_service %>" # usually "gfsd", or maybe "gfsd-IP_ADDRESS"

DAEMON="/usr/sbin/$prog"
PIDFILE="/var/run/${FILE}.pid"
LOCKFILE="/var/lock/subsys/$FILE"
OPTIONS="-cc -f /etc/gfarm2.conf -r <%= @dir_full %> <%= @hostname_str %> <%= @address_str %>"
export X509_USER_CERT=<%= @cert_path %>
export X509_USER_KEY=<%= @key_path %>

# pull in sysconfig settings
[ -f "/etc/sysconfig/$FILE" ] && . "/etc/sysconfig/$FILE"

call_daemon()
{
	# initlog is deprecated and warning is displayed since Fedora Core 4.
	if egrep -q '^[^#]*[     ]initlog' /etc/init.d/functions; then
		initlog $INITLOG_ARGS -c "$*"
	else
		$*
	fi
}

# We won't just use "killproc" and "status" function here,
# because these functions don't allow multiple server processes for
# same binary.

start()
{
	echo -n "Starting $FILE:"
	checkstatus > /dev/null
	if [ $? -eq 0 ]; then
		success
		echo
		return 0
	fi

	call_daemon $DAEMON -P $PIDFILE $OPTIONS && success || failure
	RETVAL=$?
	[ "$RETVAL" = 0 ] && touch "$LOCKFILE"
	echo
	return $RETVAL
}

stop()
{
	echo -n "Stopping $FILE:"
	checkstatus > /dev/null
	if [ $? -eq 3 ]; then
		success
		echo
		return 0
	fi

	if [ -f "$PIDFILE" ]; then
		kill -TERM `cat "$PIDFILE"` && success || failure
		RETVAL=$?
		if [ $RETVAL -eq 0 ] ||
		   [ ! -d /proc/`sed 's/[^0-9]//g' "$PIDFILE"` ]; then
			rm -f "$PIDFILE" "$LOCKFILE"
		fi
	else
		echo "$FILE is already stopped (no $PIDFILE)"
		failure
		RETVAL=1
	fi
	echo
	return $RETVAL
}

checkstatus()
{
	if [ -f "$PIDFILE" ] && [ -d /proc/`sed 's/[^0-9]//g' "$PIDFILE"` ]
	then
		echo "$FILE (pid" `cat "$PIDFILE"`") is running"
		return 0
	elif [ -f "$PIDFILE" ]; then
		echo "$FILE (pid" `cat "$PIDFILE"`") is dead, but $PIDFILE remains"
		return 1
	elif [ -f "$LOCKFILE" ]; then
		echo "$FILE is dead (no $PIDFILE), but $LOCKFILE remains"
		return 2
	else
		echo "$FILE is stopped (no $PIDFILE)"
		return 3
	fi
}

usage()
{
	echo $"Usage: $0 {start|stop|restart|status}"
	exit 1
}

RETVAL=0

SUB_COMMAND="$1"
shift

case "$SUB_COMMAND" in
  start)
	start
	RETVAL=$?
	;;
  stop)
	stop
	RETVAL=$?
	;;
  restart|reload)
	stop
	start
	RETVAL=$?
	;;
  status)
	checkstatus
	RETVAL=$?
	;;
  *)
	usage
	;;
esac

exit $RETVAL
